import os
import re

def extract_file_name(content):
    # 使用正则表达式从\verb|考生文件夹\Python\xxx|中提取xxx
    match = re.search(r'\\verb\|考生文件夹\\Python\\([^\\]+)\.py\|', content)
    if match:
        return match.group(1)
    return None

def process_question_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 提取文件名
    file_name = extract_file_name(content)
    if not file_name:
        print(f"Warning: Could not extract file name from {file_path}")
        return
    
    # 提取题目要求（在lstlisting之前的文本）
    requirement = content.split('\\begin{lstlisting}')[0].strip()
    # 清理LaTeX标记
    requirement = re.sub(r'\\newline|\\verb\|.*?\||[$\\]', '', requirement).strip()
    
    # 提取Python代码部分
    code_match = re.search(r'\\begin{lstlisting}\[language=Python\](.*?)\\end{lstlisting}', 
                          content, re.DOTALL)
    if code_match:
        code = code_match.group(1).strip()
        
        # 组合注释和代码
        final_code = f'''"""
题目要求：
{requirement}
"""

{code}'''
        
        # 直接在Python目录下创建文件
        target_file = os.path.join('Python', f"{file_name}.py")
        with open(target_file, 'w', encoding='utf-8') as f:
            f.write(final_code)
        print(f"Created {target_file}")

def main():
    # 处理所有q*.tex文件
    for filename in sorted(os.listdir('.')):
        if filename.startswith('q') and filename.endswith('.tex'):
            print(f"Processing {filename}...")
            process_question_file(filename)

if __name__ == '__main__':
    main() 
